﻿<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title></title>
	<link href="js-console.css" rel="stylesheet" />
	<!-- 3. Write a JavaScript function that finds how many 
			times a substring is contained in a given text (perform case insensitive search).
			Example: The target substring is "in".  The text is as follows:
		 
		We are living in an yellow submarine. We don't have anything else. Inside the submarine is very 
		tight. So we are drinking all the day. We will move out of it in 5 days.
		
		The result is: 9. -->
	<style>
		textarea, input, button {
			display: block;
			width: 800px;
		}
	</style>
</head>
<body>
	<input id="subStr" type="text" placeholder="Sub-string to search for" />
	<textarea id="input" placeholder="Text to search in"></textarea>
	<button onclick="doCount()">Count Substring Appearance</button>
	<div id="js-console"></div>
	<script src="js-console.js"></script>
	<script>
		function countSubstringAppearance(input, subStr) {
			var count = 0;
			var str = new String(input).toUpperCase();
			var toSerach = new String(subStr).toUpperCase();
			
			if (str.length > 0 && toSerach.length > 0) {
				var index = str.indexOf(toSerach);
				while (index >= 0) {
					count++;
					index = str.indexOf(toSerach, index + 1);
				}
			}

			return count;
		}

		function doCount() {
			// Read User input
			var input = jsConsole.read("#input");
			var subStr = jsConsole.read("#subStr");

			// Output
			jsConsole.writeLine("You have entered:");
			jsConsole.writeLine("<blockquote>" + input + "</blockquote>");

			// Do the count
			var count = countSubstringAppearance(input, subStr);
			jsConsole.writeLine("Substring '" + subStr + "' is contained " + count +
									" times in a given text.");
		}
	</script>
</body>
</html>
